User-Defined Functions

Working from the Command Window is convenient for evaluating the value of short calculations that we only need to calculate once. However, for formulas that you wish to evaluate for several different input values, it is best to define a function that you can reuse. This is known as reusability and it is a primary reason for defining your own functions. Once the function is defined and tested, you can use it as often as you want with confidence that it will return the correct value.

Matlab allows users to define their own functions by typing a function header and the commands that evaluate the function into an m-file. Review the earlier lesson on m-files for ways to create, open, and save m-files.

A user-defined function in Matlab is similar to the built-in functions you used in an earlier lesson. Most functions require one or more input values to calculate and return one or more output values. An important use of all functions is to make code more modular and thus to simplify the writing of complex solutions. This lesson will show you how to define your own functions in Matlab.

Function Definition Example

  1. Create a new directory for this function or change to an existing directory if you have one available for this lesson. See the Overview lesson for help creating directories.
  2. Create a new m-file. See the M-file lesson for help with this step.
  3. Type (or copy and paste) this code into the open editor window.
        function tempC = FtoC ( tempF )
        % This function returns the temperature in celsius
        % tempF contains the temperature to be converted, in fahrenheit
        tempC = (tempF - 32)*5/9; 
  4. Save your m-file with the name FtoC.m. Be sure to use the same name and capitalization as used for the function's name in the function header. This is the default in Matlab.
  5. Try your function

    Once you have defined a function, be sure to test the function to ensure that it works as you expect. The next lesson will explain some common things to test and how to fix any bugs you find. For now, just try your function in the Command Window. The following command should return the value 23.8889 (degrees Celsius).

        >> FtoC(75)
        

If your function did not work, check for some simple but common mistakes. Your function must be in a file named FtoC.m (same capitalization) and it must be saved in the current directory.

Array (Vector) Inputs to Functions

Many built-in Matlab functions automatically handle vector or array arguments. For example, cos(x) works whether x (input argument) is a scalar value or an array. If x is an array, then cos(x) computes the cosine of each element in x and returns an array consisting of the cosines of the corresponding elements of x. In other words, the cos function works element-wise on vector input.

You can define the functions you write to handle array input. One way to do this is to use element-wise operations within the body of your function. For example, consider this function that calculates the cube of the input value:

     function c = cube(x)
     c = x ^ 3 ;

As it is written, it only works correctly if x is a scalar value. (Test this for yourself by first writing the cube function and then, in the command window or another script, entering the command cube([1 2 3]).)

We can modify the function so it handles array input by changing the power operator ( ^ ) to the element-wise power operator ( .^ ), as shown here:

     function c = cube(x)
     c = x .^ 3 ;

Another way we can deal with array input is to use loops to iterate through each element in the array. This is less desireable than simply using element-wise operators where appropriate. You will learn about loops and iterative statements in a later lesson.

Here is a way to use the vector version of the cube function:

     clear;               % Clears all existing variables
     clf;                 % Clears the plot figure
     xx = -1 : 0.1 : 3 ;  % Create an array of values of x 
     yy = cube( xx ) ;    % Compute the function values 
     plot( xx, yy, 'r' )  % Plot the values

Multiple Return Values from Functions

The following is a valid function header:

    function [pounds, ounces] = convert_kg_to_lb_oz(kilograms)

This is the correct header for a function which wishes to return two different (scalar, vector, or matrix) variables, one called pounds and one called ounces. This a common technique when multiple values are computed by a function and need to be returned to the caller of that function. If you wish to return multiple matrices, use a comma to separate the values.

If you need to store all function results, then assign results to multiple variables, using this syntax.

    [p,o] = convert_kg_to_lb_oz(k)

Now, p will have the pounds and o will have the ounces value(s).

What happens if you assign the results of such a function to a single variable? Try this to find out.